package com.word.student.service.impl;

import java.util.Collections;
import java.util.List;

import com.word.common.utils.PageUtils;
import com.word.student.domain.WordFavorite;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
import java.util.stream.Collectors;

import com.word.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.word.student.domain.WordGroupGet;
import com.word.student.mapper.WordGetMapper;
import com.word.student.domain.WordGet;
import com.word.student.service.IWordGetService;

/**
 * 单词背诵Service业务层处理
 * 
 * @author wsccvb
 * @date 2025-05-21
 */
@Service
public class WordGetServiceImpl implements IWordGetService 
{
    @Autowired
    private WordGetMapper wordGetMapper;

    /**
     * 查询单词背诵
     * 
     * @param wordFavorite 单词背诵主键，用户主键
     * @return 单词背诵
     */
    @Override
    public WordGet selectWordGetById(WordFavorite wordFavorite)
    {
        return wordGetMapper.selectWordGetById(wordFavorite);
    }

    /**
     * 查询单词背诵列表
     * 
     * @param wordGet 单词背诵
     * @return 单词背诵
     */
    @Override
    public List<WordGet> selectWordGetList(WordGet wordGet, WordFavorite wordFavorite)
    {
        String value = wordGet.getWordGroupGetValueList().get(0);
        if (wordGet.getWordGroupGetValueList() != null && !wordGet.getWordGroupGetValueList().isEmpty()
            && !wordGet.getWordGroupGetValueList().get(0).isEmpty()) {
            PageUtils.clearPage();
            List<WordGroupGet> wordGroupGetList = wordGetMapper.selectWordGroupGetByValue(value);
            Set<Long> wordGroupGetIds = wordGroupGetList.stream()
                    .map(WordGroupGet::getWordId)
                    .collect(Collectors.toSet());
            if (wordGroupGetIds.isEmpty()) {
                return Collections.emptyList();
            }
            // 修改为批量查询
            List<WordGet> ans = wordGetMapper.selectWordGetByIds(
                new java.util.ArrayList<>(wordGroupGetIds), 
                wordFavorite.getUserId()
            );
            PageUtils.startPage();
            return ans;
        }
        return wordGetMapper.selectWordGetList(wordGet, wordFavorite);
    }


    @Override
    @Transactional
    public boolean toggleCollect(WordFavorite wordFavorite) {
        if (wordGetMapper.checkCollected(wordFavorite)) {
            wordGetMapper.deleteCollect(wordFavorite);
            return false;
        } else {
            wordGetMapper.insertCollect(wordFavorite);
            return true;
        }
    }

    @Override
    public List<WordGet> selectWordGetListByIds(List<Long> ids, Long userId) {
        if (ids == null || ids.isEmpty()) {
            return Collections.emptyList();
        }
        return wordGetMapper.selectWordGetByIds(ids, userId);
    }
}
